(function () {
    "use strict";

    var app = angular.module('han.message', []);
    var DefaultOptions = {
        RECONNECT_TIMEOUT: 10000,		// 10秒断线重连
        SERVER: '/ecar/socket',			// socket连接地址
        BROKER_PREFIX: '/ecar/broker',	// 服务器broker前缀
        TOPIC_PREFIX: '/topic',			// 订阅通知的前缀
        onconnect: null,				// 连接成功回掉
        onclose: null,					// 连接断开回掉
        keepalive: true,				// 断线重连
        debug: null,                    // debug模式处理
    };

    HanMsg.$inject = ['$rootScope', '$q', '$timeout', 'hanMsgOptions'];
    function HanMsg($rootScope, $q, $timeout, hanMsgOptions) {
        var _opts = hanMsgOptions;
        var _socket = {
            client: null,
            stomp: null,
        };

        return {
			/**
			 * 发送消息
			 * topic 消息地址uri
			 * data 消息内容（json对象）
			 * priority 优先级
			 */
            send: function (topic, data, priority) {
                priority = priority || 9;
                return _socket.stomp.send(_opts.BROKER_PREFIX + topic, { priority: priority }, JSON.stringify(data));
            },

			/**
			 * 订阅消息
			 * 参数：
			 *	topic 订阅消息地址，处理订阅消息，使用.then(callback)
			 * 返回 deferred.promise;
			 */
            subscribe: function (topic, callback, prefix) {
                prefix = prefix || _opts.TOPIC_PREFIX;
                return _socket.stomp.subscribe(prefix + topic, callback);
            },

			/**
			 * 初始化socket
			 * opts: 配置，未指定则使用默认配置
			 */
            initialize: function (opts) {
                if (opts) _opts = angular.extend({}, _opts, opts);
                if (_socket.stomp) _socket.stomp.disconnect();
                if (_socket.client) _socket.client.close();

                _socket.client = new SockJS(_opts.SERVER);
                _socket.stomp = Stomp.over(_socket.client);

                if (typeof _opts.debug === "function") {
                    _socket.stomp.debug = _opts.debug;
                } else if (_opts.debug !== "true" && _opts.debug !== true) {
                    _socket.stomp.debug = null;
                }
                _socket.stomp.connect({}, _opts.onconnect);
            },

			/**
			 * 断开连接
			 */
            disconnect: function (opts) {
                if (opts) _opts = angular.extend({}, _opts, opts);

                var thiz = this;
                var reconnect = function () {
                    $timeout(function () {
                        thiz.initialize();
                    }, _opts.RECONNECT_TIMEOUT);
                };

                _opts.onclose = _opts.onclose || reconnect;
                if (_opts.keepalive) {
                    if (_socket.stomp) _socket.stomp.disconnect(_opts.onclose);
                } else {
                    if (_socket.stomp) _socket.stomp.disconnect();
                    _socket.stomp = null;
                    if (_socket.client) _socket.client.close();
                    _socket.client = null;
                }
            }
        };
    }

    app.value('hanMsgOptions', DefaultOptions);
    app.factory('hanMsg', HanMsg);
}).call(this);